package com.example.demo.msg.nio;/**
 * Created by kete on 2018-08-10.
 */


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 作者：kete
 * 创建时间：2018-08-10 17:28
 * 功能描述：
 * 版本：
 */
public class ClientHandle implements Runnable{

    private Selector selector;

    private SocketChannel socketChannel;

    private volatile boolean started;

    public ClientHandle() {
        try {
            selector = Selector.open();

            socketChannel = SocketChannel.open();

            socketChannel.configureBlocking(false);

            started = true;
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {

        try {
            doConnection();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while (started){

            try {
                selector.select(1000);

                Set<SelectionKey> keys = selector.selectedKeys();

                Iterator<SelectionKey> it= keys.iterator();

                SelectionKey key = null;
                while (it.hasNext()){
                    key = it.next();
                    it.remove();


                    try {
                        handleKey(key);
                    } catch (IOException e) {
                        e.printStackTrace();
                        if(key!=null){
                            key.cancel();
                            if(key.channel()!=null){
                                key.channel().close();
                            }
                        }
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }

        }

        if(selector!=null){
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void handleKey(SelectionKey key) throws IOException{
        if(key.isValid()){

            SocketChannel sc = (SocketChannel)key.channel();

            if(key.isConnectable()){
                if(sc.finishConnect());
                else System.exit(1);
            }
            if(key.isReadable()){

                ByteBuffer bf = ByteBuffer.allocate(1024);

                int readBytes = sc.read(bf);

                if(readBytes>0){

                    bf.flip();
                    byte[] bytes = new byte[bf.remaining()];
                    bf.get(bytes);

                    String exproess = new String(bytes,"utf-8");

                    System.out.printf("客户端收到 消息:"+exproess);


                }else if(readBytes<0){
                    key.cancel();
                    sc.close();
                }

            }
        }
    }

    public void stop (){
        started = false;
    }

    private void doConnection() throws IOException{

        if(socketChannel.connect(new InetSocketAddress("127.0.0.1",SocketServer.port)));
        else socketChannel.register(selector, SelectionKey.OP_CONNECT);


    }

    protected void send(String msg) throws Exception{

        socketChannel.register(selector, SelectionKey.OP_READ);

        byte[] writeBytes = msg.getBytes("utf-8");

        ByteBuffer wrBf = ByteBuffer.allocate(writeBytes.length);
        wrBf.put(writeBytes);

        wrBf.flip();

        socketChannel.write(wrBf);
    }

}
